---
title: Next.js
description: Ratelimiting endpoints with Next.js
mode: "wide"
---

## Prerequisites

- Created your [Unkey account](https://app.unkey.com/auth/sign-up)
- Created an [Unkey root key](https://app.unkey.com/settings/root-keys) with the following permissions:
  - `ratelimit.*.create_namespace` - to create namespaces
  - `ratelimit.*.limit` - to check rate limits


<Steps titleSize="h3">

<Step title="Create Next.js Application">
Run the following command to init your Next.js project

<CodeGroup>

```bash npm
npx create-next-app@latest
```

```bash pnpm
pnpm create next-app@latest
```

```bash yarn
yarn create-next-app@latest
```

```bash bun
bunx create-next-app
```

</CodeGroup>

</Step>
<Step  title="Install">

Now install the `@unkey/ratelimit` package

<CodeGroup>

```bash npm
npm install @unkey/ratelimit
```

```bash pnpm
pnpm add @unkey/ratelimit
```

```bash yarn
yarn add @unkey/ratelimit
```

```bash bun
bun install @unkey/ratelimit
```

</CodeGroup>

</Step>

<Step  title="Add Root Key to env">

Add your root key to your `.env` file

```bash
UNKEY_ROOT_KEY="YOUR_KEY"
```

</Step>

<Step  title="Creating a protected route">

Create a new route and add the following code

```ts /app/protected/route.ts
import { NextResponse } from 'next/server';
import { Ratelimit } from "@unkey/ratelimit";


if (!process.env.UNKEY_ROOT_KEY) {
  throw new Error("UNKEY_ROOT_KEY environment variable is not set");
}

const limiter = new Ratelimit({
  namespace: "next-example",
  limit: 2,
  duration: "30s",
  rootKey: process.env.UNKEY_ROOT_KEY
});

export const POST = async (req: Request) => {
  // Extract user identifier from request headers
  // Use any identifier: userId, visitorId, IP address, etc.
  const identifier = req.headers.get('x-user-id') ?? 'anonymous';

  const ratelimit = await limiter.limit(identifier);

  if (!ratelimit.success) {
    return NextResponse.json(
      { error: "Please try again later" },
      { status: 429 }
    );
  }

  return NextResponse.json({ message: "Hello!" });
};
```

</Step>

<Step title="Running it">

<CodeGroup>

```bash npm
npm run dev
```

```bash pnpm
pnpm run dev
```

```bash yarn
yarn run dev
```

```bash bun
bun run dev
```

</CodeGroup>

</Step>

<Step  title="Try it out">

Test your ratelimited endpoint:

```bash
curl -XPOST 'http://localhost:3000/protected' \
  -H "x-user-id: test-user"
```

You will need to curl a few times to see the ratelimiting error. Once you do, you, you will need to wait to perform the action again.


</Step>

</Steps>

## What is next?

Now that you've seen the power of Unkey ratelimiting, check out some resources below to continue your journey.

<CardGroup cols={3}>
  <Card title="Discord" icon="discord" href="https://unkey.com/discord">Join our Discord to chat with us and the community</Card>
  <Card title="Ratelimit SDK" icon="brackets-curly" href="/libraries/ts/ratelimit/ratelimit">
     Explore advanced SDK features like timeouts, error handling, and custom costs.
  </Card>
  <Card title="API Reference" icon="database" href="/api-reference/v2/overview">
     Learn about our v2 API for managing APIs, keys, ratelimits and analytics.
  </Card>
</CardGroup>
